package com.fh.modules.ss.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.api.vo.Result;
import com.fh.common.aspect.annotation.AutoLog;
import com.fh.common.constant.CommonConstant;
import com.fh.common.exception.Assert;
import com.fh.common.query.QueryWrapperUtil;
import com.fh.common.util.ConvertUtils;
import com.fh.modules.ss.entity.SsMaterialInst;
import com.fh.modules.ss.entity.SsMaterialLeaseRecord;
import com.fh.modules.ss.service.ISsMaterialInstService;
import com.fh.modules.ss.service.ISsMaterialLeaseRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Title: Controller
 * @Description: 租赁记录
 * @author： code generator
 * @date：   2019-09-07
 * @version： V1.0
 */
@RestController
@RequestMapping("/ss/ssMaterialLeaseRecord")
@Slf4j
@Api("租赁记录")
public class SsMaterialLeaseRecordController {
	@Autowired
	private ISsMaterialLeaseRecordService ssMaterialLeaseRecordService;

	 @Autowired
	 private ISsMaterialInstService ssMaterialInstService;
	
	/**
	  * 分页列表查询
	 * @param ssMaterialLeaseRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	@ApiOperation("分页列表查询")
	@AutoLog(value="租赁记录分页查询",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result queryPageList(SsMaterialLeaseRecord ssMaterialLeaseRecord,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		QueryWrapper<SsMaterialLeaseRecord> queryWrapper = new QueryWrapper<SsMaterialLeaseRecord>();
		ssMaterialLeaseRecord.setDelFlag(CommonConstant.DEL_FLAG_0);
		QueryWrapperUtil.initQueryWrapper(queryWrapper, ssMaterialLeaseRecord);
		Page<SsMaterialLeaseRecord> page = new Page<SsMaterialLeaseRecord>(pageNo, pageSize);
		IPage<SsMaterialLeaseRecord> pageList = ssMaterialLeaseRecordService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	  *   添加
	 * @param ssMaterialLeaseRecord
	 * @return
	 */
	@PostMapping(value = "/add")
	@ApiOperation("添加")
	@AutoLog("添加租赁记录")
	public Result add(@RequestBody SsMaterialLeaseRecord ssMaterialLeaseRecord) {
		Assert.isTrue(ssMaterialLeaseRecord.getReceiveNum()==0||ssMaterialLeaseRecord.getSendNum()==0, "数量不能为0");
		Assert.isTrue(ssMaterialLeaseRecord.getReceiveNum()>ssMaterialLeaseRecord.getSendNum(), "接收数量不能大于发货数量");
		SsMaterialInst ssMaterialInst = ssMaterialInstService.getById(ssMaterialLeaseRecord.getMaterialId());
		ssMaterialLeaseRecord.setName(ssMaterialInst.getName());
		ssMaterialLeaseRecord.setUnit(ssMaterialInst.getUnit());
		ssMaterialLeaseRecord.setUnitName(ssMaterialInst.getUnitName());
		ssMaterialLeaseRecord.setUnitPrice(ssMaterialInst.getUnitPrice());
		ssMaterialLeaseRecord.setMaterialTypeName(ssMaterialInst.getTypeName());
		ssMaterialLeaseRecord.setDelFlag(CommonConstant.DEL_FLAG_0);
		ssMaterialLeaseRecordService.save(ssMaterialLeaseRecord);
		return Result.ok("添加成功");
	}
	
	/**
	  *  编辑
	 * @param ssMaterialLeaseRecord
	 * @return
	 */
	@PutMapping(value = "/edit")
	@ApiOperation("修改")
	@AutoLog("修改租赁记录")
	public Result edit(@RequestBody SsMaterialLeaseRecord ssMaterialLeaseRecord) {
		SsMaterialInst ssMaterialInst = ssMaterialInstService.getById(ssMaterialLeaseRecord.getMaterialId());
		ssMaterialLeaseRecord.setName(ssMaterialInst.getName());
		ssMaterialLeaseRecord.setUnit(ssMaterialInst.getUnit());
		ssMaterialLeaseRecord.setUnitName(ssMaterialInst.getUnitName());
		ssMaterialLeaseRecord.setUnitPrice(ssMaterialInst.getUnitPrice());
		ssMaterialLeaseRecord.setMaterialTypeName(ssMaterialInst.getTypeName());
		boolean ok = ssMaterialLeaseRecordService.updateById(ssMaterialLeaseRecord);
		return ok?Result.ok("修改成功"):Result.error("修改失败");
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	@ApiOperation("通过id删除")
	@AutoLog("删除租赁记录")
	public Result delete(@RequestParam(name="id",required=true) String id) {
		ssMaterialLeaseRecordService.deleteEntityByDelFlag(id);
		return Result.ok("删除成功");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	@ApiOperation("批量删除")
	@AutoLog("批量删除租赁记录")
	public Result deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		ssMaterialLeaseRecordService.deleteBatchEntityByDelFlag(ids);
		return Result.ok("批量删除成功");
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	@ApiOperation("通过id查询")
	@AutoLog(value="租赁记录通过id查询",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result queryById(@RequestParam(name="id",required=true) String id) {
		SsMaterialLeaseRecord ssMaterialLeaseRecord = ssMaterialLeaseRecordService.getById(id);
		return Result.ok(ssMaterialLeaseRecord);
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  @ApiOperation("导出excel")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<SsMaterialLeaseRecord> queryWrapper = new QueryWrapper<SsMaterialLeaseRecord>();
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (ConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              SsMaterialLeaseRecord ssMaterialLeaseRecord = JSON.parseObject(deString, SsMaterialLeaseRecord.class);
              QueryWrapperUtil.initQueryWrapper(queryWrapper, ssMaterialLeaseRecord);
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<SsMaterialLeaseRecord> pageList = ssMaterialLeaseRecordService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "租赁记录列表");
      mv.addObject(NormalExcelConstants.CLASS, SsMaterialLeaseRecord.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("租赁记录列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  @ApiOperation("通过excel导入")
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<SsMaterialLeaseRecord> listSsMaterialLeaseRecords = ExcelImportUtil.importExcel(file.getInputStream(), SsMaterialLeaseRecord.class, params);
              for (SsMaterialLeaseRecord ssMaterialLeaseRecordExcel : listSsMaterialLeaseRecords) {
                  ssMaterialLeaseRecordService.save(ssMaterialLeaseRecordExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listSsMaterialLeaseRecords.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
